import { useMainStore } from '@/store/index'
import dayjs from 'dayjs'
import { adminLogout } from '@/services/auth.service'
import { defineStore } from 'pinia'

export const useAuthStore = defineStore('auth', {
  state: () => ({
    isLogin: false,
    token: '',
    expire: 0,
    expireTime: 0,
    inited: false,
    user: {
      ok: false
    }
  }),
  getters: {
    loginToken (state) {
      const now = dayjs().unix()
      if (state.expireTime <= now) {
        return ''
      }
      return state.token
    }
  },
  actions: {
    // 初始化状态
    initSession () {
      const adminInfo = sessionStorage.getItem('admin_info')
      if (!adminInfo) {
        return
      }
      try {
        const info = JSON.parse(window.atob(adminInfo))
        this.isLogin = true
        this.token = info.token
        this.expire = info.expire
        this.expireTime = info.expireTime
      } catch (e) {
      }
    },
    // 保存登陆凭证信息
    saveAuthInfo (auth: AuthLoginResponse) {
      const store = useMainStore()
      this.isLogin = true
      this.token = auth.token
      this.expire = auth.expire
      this.expireTime = dayjs().unix() + auth.expire
      sessionStorage.setItem('admin_info', window.btoa(JSON.stringify({
        token: this.token,
        expire: this.expire,
        expireTime: this.expireTime
      })))
      store.initMenu()
    },
    setInit (val: boolean) {
      this.inited = val
    },
    // 注销登陆
    async logout () {
      try {
        await adminLogout()
      } finally {
        this.inited = false
        this.isLogin = false
        this.token = ''
        this.expire = 0
        this.expireTime = 0
        sessionStorage.removeItem('admin_info')
      }
    },
    setUser (user: AuthCheckInfo) {
      this.user = user
    }
  }
})
